package simi;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

//import org.apache.commons.net.telnet.EchoOptionHandler;
//import org.apache.commons.net.telnet.InvalidTelnetOptionException;
//import org.apache.commons.net.telnet.TelnetClient;
//import org.apache.commons.net.telnet.TerminalTypeOptionHandler;
import com.sshtools.j2ssh.SshClient;
import com.sshtools.j2ssh.session.SessionChannelClient;
import com.sshtools.j2ssh.authentication.PasswordAuthenticationClient;
import com.sshtools.j2ssh.authentication.AuthenticationProtocolState;

public class SetupSessionServlet extends HttpServlet { 
	private static final long serialVersionUID = 1L;
	//private static long limitToPrompt = SimiPropertyManager.getConfig().getLong("connection.timeLimitToPrompt");
	
	public void doPost(HttpServletRequest req, HttpServletResponse res){	
		try {
			// If user hasn't been set up with a session...
			HttpSession theSession = req.getSession();
			boolean Prompt = true;
			if(theSession.getAttribute(Constants.SESSION) == null)Prompt = setupSession(req, theSession);
			//if(Prompt)System.out.println("simi: session is set up");
			if(Prompt)getServletConfig().getServletContext().getRequestDispatcher("/SetupModels").forward(req, res);
			else getServletConfig().getServletContext().getRequestDispatcher("/logout.jsp").forward(req, res);	
		}catch (InterruptedException ie){
			ie.printStackTrace();
		}catch (ServletException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private boolean setupSession(
		HttpServletRequest req, 
		HttpSession theSession
	)throws IOException, InterruptedException {
		String host = SimiPropertyManager.getConfig().getString("connection.host");	
		String command = SimiPropertyManager.getConfig().getString("connection.command");
		String username = req.getParameter("username");
		String password = req.getParameter("password"); 
		SshClient ssh = new SshClient();
		ssh.connect(host);
		PasswordAuthenticationClient pwd = new PasswordAuthenticationClient();
		pwd.setUsername(username);
		pwd.setPassword(password);
		int result = ssh.authenticate(pwd);
		if(result!=AuthenticationProtocolState.COMPLETE) return false;
		SessionChannelClient session = ssh.openSessionChannel();//not to be confused with "theSession"
		if(!(session.requestPseudoTerminal("ansi",80,24,0,0,""))) return false;
		session.executeCommand(command);			
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		IOUtil iou = new IOUtil();
		iou.readWrite(session.getInputStream(), baos);	
		OutputStream os = session.getOutputStream();
		theSession.setAttribute(Constants.SESSION, session);
		theSession.setAttribute(Constants.SESSION_OUTPUT_STREAM, os);  	
		theSession.setAttribute(Constants.RUNNING_OUTPUT_PARAM, baos);
		theSession.setAttribute(Constants.SESSION_INPUT_STREAM, session.getInputStream());   	
		theSession.setAttribute("username", username);
		//theSession.setAttribute("password", password); // maybe unsafe
		String homeDirPrefix = SimiPropertyManager.getConfig().getString("files.home");
		theSession.setAttribute("homedir", homeDirPrefix + username + "/");
		String restrictPrefix = SimiPropertyManager.getConfig().getString("files.restrict");
		theSession.setAttribute("restrict", restrictPrefix + username);
		theSession.setAttribute("connection",ssh);
		return true;
			
	}
}